package kevin.luo.DAL;

import java.util.ArrayList;
import java.util.List;

import kevin.luo.DAL.DTO.Order;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class OrderService extends  BaseService {
	public OrderService(Context context)
	{
		super(context);
	}
public List<Order> SingleOrder(String where,String[] args)
{
	List<Order> orders=new ArrayList<Order>();

	Cursor cursor = super.db.getReadableDatabase().rawQuery(Table.TB_ORDER+" WHERE "+where,args);
	
	while(cursor.moveToNext()) {
		Order o=new Order();
	    o.setID(cursor.getInt(cursor.getColumnIndex("ID")));
	    o.setOrderID(cursor.getString(cursor.getColumnIndex("OrderID")));
	    o.setNumber(cursor.getInt(cursor.getColumnIndex("Number")));
	    o.setSumMoney(cursor.getFloat(cursor.getColumnIndex("SumMoney")));
	    o.setCreateTime(cursor.getString(cursor.getColumnIndex("CreateTime")));
	    orders.add(o);
	}
	return orders;
}
public List<Order> SingleOrderByOrderID(String orderID)
{
	return this.SingleOrder(" OrderID=?", new String[]{orderID});
}

public boolean Insert(List<Order> orders) throws Exception
{
	boolean result=false;
	try{
	SQLiteDatabase writeDB=db.getWritableDatabase();
	for(Order o:orders){
	ContentValues cv = new ContentValues();
	cv.put("ID", o.getID());
	cv.put("OrderID", o.getOrderID());
	cv.put("Number", o.getNumber());
	cv.put("SumMoney", o.getSumMoney());
	cv.put("CreateTime", o.getCreateTime());
	writeDB.insert(Table.TB_ORDER, null, cv);
	}
	result=true;
	}
	catch(Exception ex)
	{throw ex;}
	return result;

}
public boolean Update(List<Order> orders) throws Exception
{
	boolean result=false;
	try{
	this.DeleteByOrderID(orders.get(0).getOrderID());
	this.Insert(orders);
	result=true;
	}
	catch(Exception ex)
	{
		throw ex;
			}
	return result;

}

public boolean DeleteByOrderID(String OrderID) throws Exception
{
	boolean result=false;
	try{
	SQLiteDatabase writeDB=db.getWritableDatabase();
	writeDB.delete(Table.TB_ORDER, "OrderID=?", new String[]{OrderID});
	result=true;
	}
	catch(Exception ex)
	{
		throw ex;
			}
	return result;

}

public boolean Delete(String whereClause,String[] whereArgs) throws Exception
{
	boolean result=false;
	try{
	SQLiteDatabase writeDB=db.getWritableDatabase();
	writeDB.delete(Table.TB_ORDER, whereClause, whereArgs);
	result=true;
	}
	catch(Exception ex)
	{
		throw ex;
			}
	return result;

}
}
